import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable, TableDropdown } from '@ant-design/pro-components';
import { Button, Image, Grid, message } from 'antd';
import { useRef } from 'react';
import CurrentUser = API.CurrentUser;
import { searchUsers } from "@/services/ant-design-pro/api";

const { useBreakpoint } = Grid;

const columns: ProColumns<CurrentUser>[] = [
  {
    dataIndex: 'id',
    valueType: 'indexBorder',
    width: 48,
  },
  {
    title: '编号',
    dataIndex: 'planetCode',
    copyable: true,
    search: false,
  },
  {
    title: '用户账户',
    dataIndex: 'userAccount',
    copyable: true,
    search: false,
  },
  {
    title: '头像',
    dataIndex: 'avatarurl',
    render: (_, record) => (
      <div>
        <Image src={record.avatarurl} width={50} />
      </div>
    ),
    search: false,
  },
  {
    title: '性别',
    dataIndex: 'gender',
    valueType: 'select',
    valueEnum: {
      0: { text: '女' },
      1: { text: '男' },
    },
    search: false,
  },
  {
    title: '电话',
    dataIndex: 'phone',
    copyable: true,
    search: false,
  },
  {
    title: '邮件',
    dataIndex: 'email',
    copyable: true,
    search: false,
  },
  {
    title: '角色',
    dataIndex: 'userRole',
    valueType: 'select',
    valueEnum: {
      0: { text: '普通用户', status: 'Default' },
      1: {
        text: '管理员',
        status: 'Success',
      }
    },
    search: false,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    valueType: 'dateTime',
    search: false,
  },
  {
    title: '操作',
    valueType: 'option',
    key: 'option',
    render: (text, record, _, action) => [
      <Button
        key="view"
        type="link"
        size="small"
        onClick={() => {
          message.info(`查看用户: ${record.userAccount}`);
        }}
      >
        查看
      </Button>,
      <TableDropdown
        key="actionGroup"
        onSelect={(key) => {
          if (key === 'copy') {
            const userInfo = `用户账户: ${record.userAccount}, 编号: ${record.planetCode}, 角色: ${record.userRole === 1 ? '管理员' : '普通用户'}`;
            navigator.clipboard.writeText(userInfo);
            message.success('用户信息已复制到剪贴板');
          }
        }}
        menus={[
          { key: 'copy', name: '复制信息' },
        ]}
      />,
    ],
  },
];

export default () => {
  const actionRef = useRef<ActionType>();
  const screens = useBreakpoint();

  return (
    <ProTable<CurrentUser>
      columns={columns}
      actionRef={actionRef}
      cardBordered
      // 简化请求，只获取列表数据，不传递任何搜索参数
      request={async (params = {}) => {
        try {
          console.log('请求参数:', params);

          // 只传递分页参数，不传递任何搜索条件
          const userList = await searchUsers({
            current: params.current,
            pageSize: params.pageSize,
          });

          return {
            data: userList,
            success: true,
          };
        } catch (error) {
          message.error('数据加载失败');
          return {
            data: [],
            success: false,
          };
        }
      }}
      editable={{
        type: 'multiple',
      }}
      columnsState={{
        persistenceKey: 'user-management-table',
        persistenceType: 'localStorage',
        defaultValue: {
          option: { fixed: 'right', disable: true },
        },
        onChange(value) {
          console.log('value: ', value);
        },
      }}
      rowKey="id"
      // 完全禁用搜索功能
      search={false}
      options={{
        setting: {
          listsHeight: 400,
        },
        density: true,
        fullScreen: true,
        reload: true,
      }}
      // 移除表单同步配置
      pagination={{
        pageSize: screens.xs ? 5 : 10,
        showSizeChanger: !screens.xs,
        showQuickJumper: !screens.xs,
        onChange: (page) => console.log(page),
      }}
      dateFormatter="string"
      headerTitle="用户列表"
      // 工具栏只保留刷新按钮
      toolBarRender={() => [
        <Button
          key="refresh"
          onClick={() => {
            actionRef.current?.reload();
          }}
          type="primary"
        >
          刷新
        </Button>,
      ]}
    />
  );
};
